<script setup lang="ts">
import {
  useMessage,
  NButton,
  NSpace,
  NDataTable,
  NInput,
  type DataTableColumns,
  NPagination,
  NModal,
  NForm,
  NFormItem,
  NSelect,
  NEllipsis
} from 'naive-ui'
import { onActivated, onMounted, reactive, ref, h, watch,onDeactivated } from 'vue'
import { sendRequest } from '@/utils/api'
import type { baseCollectClassificationConfigModel } from '@/api/baseCollectClassificationConfig'
import type { HttpResponse, HttpResponsePagination } from '@/utils/http'
import TableView from '@/components/TableView.vue'
// @ts-ignore
import Sortable from 'sortablejs'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { useRoute, useRouter } from 'vue-router'

const message = useMessage()
const router = useRouter()
const listOption = ref([])
onActivated(() => {
  if (window.flags.flushRole) {
    queryTableData(true)
    window.flags.flushRole = false
  }
})

const tableData = ref<baseCollectClassificationConfigModel[]>([])
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})
type Reset = () => void
function useQueryForm<T = unknown>(form: T, reset: Reset): [form: T, reset: Reset] {
  return [form, reset]
}
const modalVisible = ref(false)
const route = useRoute()
const [form, resetForm] = useQueryForm(
  reactive({
    startDate: null,
    endDate: null,
    key: null,
    statusCode: null
  }),
  () => {
    form.startDate = null
    form.endDate = null
    form.key = null
    form.statusCode = null
  }
)
const tableRef = ref()
const setSort = () => {
  if (tableRef.value) {
    const el = tableRef.value?.$el.querySelector('.n-data-table-tbody')
    Sortable.create(el, {
      onEnd: (evt: any) => {
        const targetRow = tableData.value.splice(evt.oldIndex, 1)[0]
        tableData.value.splice(evt.newIndex, 0, targetRow)
      }
    })
  }
}
const columns: DataTableColumns<baseCollectClassificationConfigModel> = [
  {
    type: 'selection',
    fixed: 'left',
    width: '2rem'
  },
  {
    title: '序号',
    key: 'orderIndex',
    render: (e, i) => {
      if(e.parentCode==="T"){
        return ++i + (paginationReactive.page - 1) * paginationReactive.pageSize
      }
    },
    width: '5rem',
    align: 'center'
  },
  {
    title: '分类名称',
    key: 'classificationName',
    width: '10rem',
    align: 'center',
  },
  {
    title: '状态',
    key: 'statusName',
    width: '10rem',
    align: 'center'
  },
  {
    title: '备注',
    key: 'notes',
    width: '15rem',
    align: 'center',
    render:(e:any)=>{
      return h(
        NEllipsis,
        {
          style:{
            minWidth: '15rem'
          }
        },
        {
          default:()=>e.notes
        }
      )
    }
  },
  {
    title: '操作',
    key: 'action',
    width: '20rem',
    align: 'center',
    fixed: 'right',
    render: (e: any) => [
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => handleEdit(e)
        },
        {
          default: () => '编辑'
        }
      ),
      h(
        NButton,
        {
          type: 'primary',
          quaternary: true,
          onClick: () => handleDetail(e)
        },
        {
          default: () => '详情'
        }
      ),
      h(
        NButton,
        {
          type: 'error',
          quaternary: true,
          onClick: () => handleDelete(e.id)
        },
        {
          default: () => '删除'
        }
      )
    ]
  }
]
const tableLoading = ref(false)
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  const [error, res] = await sendRequest<
    HttpResponsePagination<baseCollectClassificationConfigModel>
  >({
    module: 'baseCollectClassificationConfig',
    api: 'listAll',
    override: {
      params: {
        key: form.key,
        statusCode: form.statusCode
      }
    }
  })
  tableLoading.value = false

  if (error) return message.error(error.message)
  // @ts-ignore
  tableData.value = res.data
  setSort()
}
//下拉
const getFunction = async () => {
  listOption.value = []
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'baseCollectClassificationConfig',
    api: 'listByParentCode',
    override: {
      params: {
        dicCode: 'A49'
      }
    }
  })
  if (error) return message.error(error.message)
  res.data.forEach((i: any) => {
    // @ts-ignore
    listOption.value.push({ label: i.dicName, value: i.dicCode })
  })
}
const handleEdit = (e: any) => {
  router.push({ name: 'ClassificationEdit', params: { id: e.id } })
}
const handleDetail = (e: any) => {
  router.push({ name: 'ClassificationDetail', params: { id: e.id } })
}
const handleAdd = () => {
  router.push({ name: 'ClassificationAdd' })
}
const ids = ref()
const idDDel=ref(false)
const handleDelete = (id: any) => {
  ids.value = id
  idDDel.value=false
  modalVisible.value = true
}
const againDelete = async () => {
  const [error,res] = await sendRequest<HttpResponse>({
    module: 'baseCollectClassificationConfig',
    api: 'delete',
    override: {
      data: deleteId.value.length > 0&&idDDel.value ? deleteId.value : [ids.value]
    }
  })
  if (error) return message.error(error.message)
  if(res.code!==0) return message.error(res.msg)
  queryTableData(true)
  modalVisible.value = false
  message.success('删除成功！')
  rowKeys.value = []
  deleteId.value = []
}
const rowKey: any = (row: any) => row.id || ''
const rowKeys = ref([])
const deleteId = ref([])
const rowKeysChange = (v: any) => {
  rowKeys.value = v
  deleteId.value = v
}
const BatchDelete = () => {
  if (deleteId.value.length === 0) return message.warning('请至少选择一项！')
  idDDel.value=true
  modalVisible.value = true
}
onMounted(() => {
  getFunction()
  queryTableData(true)
  setTimeout(() => {
    setSort()
  }, 500)
})
const keyUpDown = (e: any) => e.key == 'Enter' && (paginationReactive.page = 1,queryTableData(true))
onDeactivated(() => window.removeEventListener('keyup', keyUpDown, false))
watch(
  () => route,
  () => {
    if (route.path == '/collectionManagement/CollectionManage/Classification/index') {
      queryTableData(true)
      window.addEventListener('keyup', keyUpDown, false)  // 回车
    }
  },
  { deep: true, immediate: true }
)
</script>

<template>
  <TableView class="role">
    <template #form>
      <NSpace justify="space-between">
        <NForm
          :show-feedback="false"
          label-placement="left"
          inline
        >
          <NFormItem label="">
            <!-- <NInput
              placeholder="请输入分类名称"
              v-model:value="form.key"
            /> -->
          </NFormItem>
          <NFormItem label="">
            <!-- <NSelect
              :options="listOption"
              v-model:value="form.statusCode"
              placeholder="请选择启用状态"
              clearable
              style="width: 200px"
            /> -->
          </NFormItem>
          <NFormItem>
            <!-- <NButton
              type="primary"
              style="width: 78px;margin-right: 10px;"
              ghost
              @click="queryTableData(true)"
              :loading="tableLoading"
            >
              查询
            </NButton>
            <NButton
            type="primary"
              ghost
              style="width: 78px;"
              @click="resetForm"
            >
              重置
            </NButton> -->
          </NFormItem>
        </NForm>
        <NSpace align="end">
          <NButton
            type="primary"
            style="width: 115px"
            @click="handleAdd"
          >
            新增
          </NButton>
        </NSpace>
      </NSpace>
    </template>
    <template #table="props">
      <NDataTable
        ref="tableRef"
        v-bind="props"
        :data="tableData"
        :columns="columns"
        :loading="tableLoading"
        size="small"
        :bordered="false"
        children-key='childList'
        :rowKey="rowKey"
        :checked-row-keys="rowKeys"
        @update:checked-row-keys="rowKeysChange"
      />
      <NButton
        tertiary
        type="error"
        style="width: 115px; margin-top: 10px"
        @click="BatchDelete"
      >
        批量删除
      </NButton>
    </template>
    <template #pagination>
   
    </template>
  </TableView>
  <NModal :auto-focus="false" v-model:show="modalVisible">
    <VDialogContent
      @close="modalVisible = false"
      @submit="againDelete"
      title="删除提示"
    >
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要删除吗?
      </div>
    </VDialogContent>
  </NModal>
</template>

<style lang="scss" scoped>
.role {
  padding: 29rem 20rem 42rem 30rem;
  color: rgba(0, 0, 0, 0.85);
}
</style>
